<template>
  <a-modal
    ref="modal"
    width="30%"
    style="min-width:350px"
    :bodyStyle="modalStyle"
    v-model="isModel"
    :title="isShowAddForm ? '被申请人新增' : '被申请人编辑'"
    :footer="null"
  >
    <div class="title_form_style">
      <div class="title_backBtn" v-if="!isShowAddForm">
        <a-button
          type="primary"
          style="float:right"
          v-show="needChangeTarget"
          :loading="loading"
          @click="updateTargetName"
          :disabled="
            admUnitForm.targetList.length === oldTargetList.length &&
              admUnitForm.targetList.every((v, i) => v === oldTargetList[i])
          "
        >
          变更
        </a-button>
        <a-button
          type="primary"
          style="margin-right: 20px;float:right"
          :loading="loading"
          @click="changeShowAddForm(true)"
        >
          新增
        </a-button>
      </div>

      <a-form-model
        v-if="!isShowAddForm"
        ref="targetForm"
        style="margin-top:45px;"
        labelAlign="left"
        :model="admUnitForm"
      >
        <a-form-model-item
          v-if="needChangeTarget && !isShowAddForm"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
          label="被申请人"
          has-feedback
        >
          <a-tree-select
            v-model="admUnitForm.targetList"
            show-search
            style="width: 100%"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            placeholder="请选择被申请人"
            multiple
            allow-clear
            :tree-data="allUnitMap"
            :replaceFields="{ children: 'children', title: 'name', key: 'id' }"
            @search="treeSearch"
            @select="treeSelect"
          >
          </a-tree-select>
        </a-form-model-item>
      </a-form-model>

      <a-form-model v-if="isShowAddForm" ref="targetForm2" :rules="rules" labelAlign="left" :model="admUnitForm">
        <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="组织机构代码" prop="id">
          <a-input v-model="admUnitForm.id" allow-clear placeholder="请输入组织机构代码" />
        </a-form-model-item>
        <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="所属类型" prop="typeid" has-feedback>
          <a-select
            :value="admUnitForm.typeid"
            :options="targetType"
            placeholder="请选择所属类型"
            :allowClear="true"
            :showSearch="true"
            :changeOnSelect="true"
            @change="targetTypeChange"
          >
          </a-select>
        </a-form-model-item>
        <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="单位名称" prop="name" has-feedback>
          <a-input v-model="admUnitForm.name" allow-clear placeholder="请输入单位名称" />
        </a-form-model-item>
        <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="行政区域" prop="adid" has-feedback>
          <a-select
            :value="admUnitForm.adid"
            :options="myadidJson"
            placeholder="请选择所属行政区"
            :allowClear="true"
            :showSearch="true"
            :changeOnSelect="true"
            @change="selectChange"
          ></a-select>
        </a-form-model-item>
        <div class="title_centerBtn">
          <a-button style="margin-right: 20px" :loading="loading" @click="changeShowAddForm(false)">
            返回
          </a-button>
          <a-button type="primary" style="margin-right: 20px" :loading="loading" @click="saveUnit">
            保存
          </a-button>
        </div>
      </a-form-model>
    </div>
    <TargetInfoAddModal ref="targetInfoAddModalRef" @setTargetInfo="setTargetInfo"></TargetInfoAddModal>
  </a-modal>
</template>
<script>
import { tree, saveUnit } from '@/api/std/std_admunit'
import { updateTargetName } from '@/api/accept/apl_admreview'
import { nanoid } from 'nanoid'
import adidJson from '../../components/k-form-design/packages/KFormDesign/config/cascadeData.js'
import { listTartype } from '@/api/std/std_tartype'
import { queryTarType } from '@/utils/apply_config/treeCustom.js'
import { getTargetListByApplyid } from '@/api/accept/apl_target'
export default {
  props: {
    applyid: {
      type: String,
      require: true
    },
    pattern: {
      type: Number,
      require: true
    },
    needChangeTarget: {
      type: Boolean,
      require: true
    }
  },
  data () {
    return {
      isModel: false,
      labelCol: { span: 6 }, // label宽
      wrapperCol: { span: 18 }, // 组件宽
      loading: false, // 按钮显示
      allUnitMap: [], // 全部的行政管理单位
      isShowAddForm: false, // 是否显示新增的行政单位
      admUnitForm: {
        // 行政管理单位保存
        targetList: [], // 被申请人
        id: '',
        name: '',
        adid: undefined, // 行政区域
        typeid: undefined // 引用类型id
      },
      selectAdid: [],
      formData: undefined, // 传入的数据
      titleLabel: '',
      /**
       * 添加表单验证规则
       */
      rules: {
        id: [{ max: 100, message: '长度不能超过100', trigger: 'blur' }],
        name: [
          { required: true, message: '请输入单位名称', trigger: 'blur' },
          { max: 50, message: '长度不能超过50', trigger: 'blur' }
        ],
        adid: [{ required: true, message: '请选择所属行政区域', trigger: 'change' }],
        typeid: [{ required: true, message: '请选择所属类型', trigger: 'change' }]
      },
      adidJson: adidJson,
      myadidJson: {},
      modalStyle: { height: '200px', overflow: 'auto' },
      oldTargetList: [], // 表单传递的targetid信息
      targetType: [], // 被申请人类型
      constTargetList: [], // 后端查询的被申请人信息
      targetInfo: {}
    }
  },
  components: {
    TargetInfoAddModal: () => import('@/views/accept/TargetInfoAddModal.vue')
  },
  computed: {},
  async created () {
    console.log('this.pattern---', this.pattern)
    if(this.pattern == 1) {
      return
    }
    this.targetInfo = {}
    // 查询被申请人类型查询
    await this.queryTargetType()
    // 查询当前的applyid全部的被申请人信息
    await this.getTargetList()
    this.queryUnitTree()
    // 过滤当前的数据 只保留南昌的数据
    this.myadidJson = this.adidJson.cascadeData.city
      .filter(item => item.value == '360000')[0]
      .children.filter(el => el.value == '360100')[0].children
  },
  updated () {},
  methods: {
    // 父组件初始化
    f_init (formData) {
      console.log('formData1', formData)
      this.formData = formData
      this.admUnitForm.targetList = []
      // 默认被申请人是该字段的值 有组件传入进来
      if (this.formData['apl_admreview#targetadid'] != '' && this.formData['apl_admreview#targetadid'] != null) {
        const adidList = this.formData['apl_admreview#targetadid'].split(',')
        const adnameList = []
        if (this.allUnitMap && this.allUnitMap.length > 0 && adidList && adidList.length > 0) {
          let allChidList = []
          for (const unitTree of this.allUnitMap) {
            if (unitTree && unitTree.children.length > 0) {
              allChidList = allChidList.concat(unitTree.children)
            }
          }
          if (allChidList && allChidList.length > 0) {
            for (const adidItem of adidList) {
              for (const child of allChidList) {
                if (child && child.id == adidItem) {
                  adnameList.push(child.name)
                }
              }
            }
          }
        }

        // 从树中获取对应的name
        if (adidList && adnameList) {
          const targetList = []
          for (let index = 0; index < adidList.length; index++) {
            targetList.push(adidList[index] + '$' + adnameList[index])
          }
          this.admUnitForm.targetList = targetList
        }
      } else {
        this.admUnitForm.targetList = []
      }
      this.oldTargetList = this.admUnitForm.targetList
      this.isModel = true
      this.isShowAddForm = false
      this.modalStyle = { height: '200px', overflow: 'auto' }
    },
    // 获取全部被申请人类型
    async queryTargetType () {
      await listTartype().then(res => {
        if (res.code == 0 && res.data) {
          this.targetType = []
          res.data.forEach(element => {
            this.targetType.push({
              key: element.id,
              title: element.name,
              label: element.name,
              value: element.id
            })
          })
        } else {
          this.targetType = []
          console.log('查询被申请人类类型失败')
        }
      })
    },
    setTreeSlot (treeData) {
      // console.log('树形数据', treeData)
      treeData.forEach(element => {
        // 对应设置树节点的值
        element.value = element.id + '$' + element.name
        // 如果是当前的根节点的话 设置为不可以选择
        if (element.typeid == '0') {
          element.disabled = true
        } else {
          element.disabled = false
        }
        if (element.children != null && element.children != undefined && element.children.length > 0) {
          this.setTreeSlot(element.children)
        }
      })
    },
    treeSearch (search) {},
    // 获取全部的行政管理单位
    queryUnitTree () {
      tree().then(res => {
        if (res.code == 0 && res.data) {
          this.allUnitMap = res.data
          this.setTreeSlot(this.allUnitMap)
        } else {
          this.allUnitMap = []
        }
      })
    },
    // 通过applyid查询对应的数据库保存的被申请人信息
    async getTargetList () {
      await getTargetListByApplyid(this.applyid).then(res => {
        if (res.code == 0 && res.data) {
          this.constTargetList = res.data
        } else {
          this.constTargetList = []
        }
      })
    },
    // 保存新的单位
    saveUnit () {
      const _this = this
      const copyForm = JSON.parse(JSON.stringify(this.admUnitForm))
      this.$refs.targetForm2.validate(valid => {
        _this.loading = true
        if (valid) {
          if (copyForm.id == '' || copyForm.id == null || copyForm.id == undefined) {
            copyForm.id = nanoid(18)
          }
          saveUnit(copyForm).then(res => {
            _this.loading = false
            if (res.code != 0) {
              _this.queryUnitTree()
            } else {
              _this.$message.success('保存成功')
               // 更新表单的被申请人信息
               queryTarType()
              _this.queryUnitTree()
              // 清空对应的数据
              this.$refs.targetForm2.resetFields()
              _this.selectAdid = []
              _this.addUnitShow = false
              _this.changeShowAddForm()
            }
          })
        } else {
          _this.loading = false
          // 加延时器的目的是为了vue实例更新未完成，我们可能获取DOM失败的问题
          // 利用原生js的方式，获取所有失败的类名，获得一个数组，取第一个元素获取焦点
          setTimeout(() => {
            const isError = document.getElementsByClassName('has-error')
            const input = isError[0].querySelector('input')
            // console.log(input)
            if (input !== null && input !== 'undefind' && input !== '') {
              isError[0].querySelector('input').focus()
                ? isError[0].querySelector('input').focus()
                : isError[0].querySelector('input').click()
            } else {
              isError[0].querySelector('textarea').focus()
            }
          }, 10)
          return false
        }
      })
    },
    // 更新被申请人
    updateTargetName () {
      const _this = this
      const copyForm = JSON.parse(JSON.stringify(this.admUnitForm))
      let targetName = ''
      const targetNameList = []
      let targetAdid = ''
      const targetAdidList = []
      if (copyForm.targetList == null || copyForm.targetList == undefined || copyForm.targetList.length == 0) {
        this.$message.error('被申请人不能为空')
        return
      }
      for (const unitTree of this.allUnitMap) {
        if (unitTree && unitTree.children.length > 0) {
          for (const unit of unitTree.children) {
            for (const selectTarget of copyForm.targetList) {
              if (selectTarget && selectTarget.indexOf('$') > 0) {
                const nodeId = selectTarget.split('$')[0]
                const nodeName = selectTarget.split('$')[1]
                if (unit.id == nodeId) {
                  targetAdidList.push(nodeId)
                  targetNameList.push(nodeName)
                }
              }
            }
          }
        }
      }
      targetName = targetNameList.join('，')
      targetAdid = targetAdidList.join(',')
      this.$confirm({
        title: '确认变更被申请人吗？',
        onOk: () => {
          this.loading = true
          updateTargetName({ applyid: _this.applyid, targetname: targetName, targetadid: targetAdid }, this.targetInfo).then(res => {
            this.loading = false
            if (res.code == 0) {
              _this.$message.success('更新成功')
              _this.isModel = false
              this.$store.commit('setPrecessformValue', ['apl_admreview#targetadid', targetAdid])
              this.$store.commit('setPrecessformValue', ['apl_admreview#targetname', targetName])
              this.$emit('reloadForm')
            } else {
              _this.$message.error('更新失败')
            }
          })
        }
      })
    },
    selectChange (value) {
      this.admUnitForm.adid = value
    },
    treeSelect (value) {
      this.$nextTick(() => {
        if (value) {
          const adid = value.split('$')[0]
          if (!this.constTargetList.some(el => el['adid'] == adid)) {
            this.$refs.targetInfoAddModalRef.init(adid)
          }
        }
      })
    },
    setTargetInfo (targetInfo, adid) {
      this.targetInfo[adid] = targetInfo
      this.$refs.targetInfoAddModalRef.cancelTargetInfo()
    },
    targetTypeChange (value) {
      this.admUnitForm.typeid = value
    },
    changeShowAddForm (state) {
      this.isShowAddForm = state
      if (this.isShowAddForm) {
        this.modalStyle = { height: '400px', overflow: 'auto' }
      } else {
        this.modalStyle = { height: '250px', overflow: 'auto' }
      }
    }
  }
}
</script>

<style lang="less" scoped>
.title_generateBtn {
  position: absolute;
  width: 200px;
  right: 225px;
}
.title_backBtn {
  width: 100%;
  display: inline-block;
}
.title_form_style {
  position: absolute;
  min-height: 50px;
  width: 90%;
}
.title_centerBtn {
  height: 40px;
  text-align: center;
  display: flex;
  justify-content: center;
  align-content: center;
}
.title_combination {
  display: flex;
  flex-direction: row;
  align-items: center;
  flex-wrap: wrap;
  width: 80%;
}
.title {
  display: flex;
  flex-wrap: wrap;
  flex-direction: column;
  width: 100%;
}
.title_prefix {
  margin-top: 0.2%;
  width: 4px;
  height: 17px;
  background-color: #5b79fb;
}
.title_center {
  margin-left: 0.5%;
  font-size: 1.2rem;
  font-family: Source Han Sans CN;
  font-weight: 550;
  color: #232323;
  letter-spacing: 2px;
}

.operate-btn {
  margin-right: 20px;
  float: right;
}
.green-btn-color {
  background-color: #5fc064;
  color: #fff;
  border: 1px solid #ccc;
}

::v-deep .ant-modal-body {
  padding: 18px;
}
</style>
